package com.sunlands.qdcy.tongzhuo.filter;

import com.alibaba.fastjson.JSONObject;
import com.sunlands.qdcy.tongzhuo.util.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: xiyuefei
 * Date: 2017/11/24
 * Time: 下午1:05
 */
@Slf4j
@Component
@ServletComponentScan
@WebFilter(urlPatterns = "/*",filterName = "paramFilter")
public class ParamFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        ServletRequest requestWrapper = new BodyReaderHttpServletRequestWrapper(request);

        //printParams2log(requestWrapper);
        filterChain.doFilter(requestWrapper,servletResponse);
    }

    @Override
    public void destroy() {

    }

    private void printParams2log(ServletRequest servletRequest)throws IOException{
        try {
            HttpServletRequest request = (HttpServletRequest) servletRequest;

            String method = request.getMethod();
            if ("GET".equals(method)) {
                log.debug("get method ,uri =【{}】,params = 【{}】", request.getRequestURI(), request.getQueryString());
            }
            String content_type = request.getHeader("Content-Type");
            if (("POST".equals(method) || "PUT".equals(method)) && content_type!=null && content_type.indexOf("multipart") < 0) {
                Map<String, String[]> params = request.getParameterMap();
                if ( params == null ) {
                    log.debug("post method ,uri = 【{}】 ,params = 【{}】", request.getRequestURI(), "");
                }else if(params != null && params.size() == 0){
                    String body = HttpUtil.getBodyString(request);
                    log.debug("post method ,uri = 【{}】 ,params = 【{}】", request.getRequestURI(), ""+body);
                }else{
                    JSONObject paramsObj = new JSONObject();
                    for (String key : params.keySet()) {
                        paramsObj.put(key, params.get(key));
                    }
                    log.debug("post method ,uri = 【{}】 ,params = 【{}】",  request.getRequestURI(), paramsObj.toJSONString());
                }
            }
        }catch (Exception ex){
            log.error("ParamsFilter printParams2log error , ex = {}",ex);
        }
    }

}
